package com.xunmall.account.controller;

import com.octo.captcha.Captcha;
import com.xunmall.account.dto.Jcaptcha;
import com.xunmall.account.service.impl.JCaptchaServiceImpl;
import com.xunmall.base.constants.SecurityConstants;
import com.xunmall.base.controller.BaseController;
import com.xunmall.base.util.WebUtils;
import com.xunmall.base.util.encode.EncodeUtils;
import com.xunmall.security.GlobalSessionUtil;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping(value = "/v1/sy/jcaptcha")
public class JCaptchaController extends BaseController {
    /**
     * 取得验证码图片
     *
     * @param request
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/{type}", method = RequestMethod.GET)
    protected Jcaptcha getJCaptcha(@PathVariable("type") String type, HttpServletRequest request) throws ServletException, IOException {
        if (type.contains("login")) {
            String remoteAddr = WebUtils.getRemoteAddr(request);
            String sessionId = remoteAddr;
            // 1、检查验证码是否开启
            Boolean jcaptchaEbabled = JCaptchaServiceImpl.getJcaptchaEbabled(sessionId);
            if (!jcaptchaEbabled) {
                return null;
            }
        }

        Jcaptcha jcaptcha = new Jcaptcha();

        String jcaptchaId = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        String jcaptchaCode = "data:image/jpg;base64,";
        Captcha captcha = JCaptchaServiceImpl.generateCaptcha(type);
        GlobalSessionUtil.rmLoginProfileKey(jcaptchaId, SecurityConstants.CAPTCHA);
        GlobalSessionUtil.setLoginProfile(jcaptchaId, SecurityConstants.CAPTCHA, captcha, 60);

        BufferedImage bi = (BufferedImage) captcha.getChallenge();
        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
        ImageIO.write(bi, "jpg", byteArray);
        String base64Str = EncodeUtils.base64Encode(byteArray.toByteArray());
        jcaptchaCode = jcaptchaCode.concat(base64Str);

        jcaptcha.setJcaptchaId(jcaptchaId);
        jcaptcha.setJcaptchaCode(jcaptchaCode);

        return jcaptcha;
    }
}